package repository

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/NULL"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEnv"
	"go-fox-edge-kernel-manager/component"
	"go-fox-edge-kernel-manager/utils/ProcessUtils"
)

type repoLocalAppSysService struct {
}

func (e *repoLocalAppSysService) GetSysProcessList() []map[string]interface{} {
	mapList := make([]map[string]interface{}, 0)

	valueConfig, err := component.ManageConfigService.GetConfigValueThis("systemProcessConfig")
	if err != nil {
		return mapList
	}

	mysqlServer := Map.GetString(valueConfig, "mysql-server", "")
	mariaServer := Map.GetString(valueConfig, "maria-server", "")
	redisServer := Map.GetString(valueConfig, "redis-server", "")
	nacosServer := Map.GetString(valueConfig, "nacos-server", "")
	nodeRed := Map.GetString(valueConfig, "node-red", "")

	appMap := NULL.Type(make(map[string]interface{}))

	// 获得进程信息：mysqlServer
	if !Method.HasEmpty(mysqlServer) {
		appMap = e.getAppInfo("kernel", "mysql-server", mysqlServer, true)
		if !Method.HasEmpty(appMap) {
			mapList = append(mapList, appMap)
		}
	}

	// 获得进程信息：mariaServer
	if !Method.HasEmpty(mariaServer) {
		appMap = e.getAppInfo("kernel", "maria-server", mariaServer, true)
		if !Method.HasEmpty(appMap) {
			mapList = append(mapList, appMap)
		}
	}

	// 获得进程信息：redisServer
	if !Method.HasEmpty(redisServer) {
		appMap = e.getAppInfo("kernel", "redis-server", redisServer, true)
		if !Method.HasEmpty(appMap) {
			mapList = append(mapList, appMap)
		}
	}

	// 获得进程信息：nacosServer
	if !Method.HasEmpty(nacosServer) && edgeEnv.GetWorkMode() == "cloud" {
		appMap = e.getAppInfo("kernel", "nacos-server", nacosServer, true)
		if !Method.HasEmpty(appMap) {
			mapList = append(mapList, appMap)
		}
	}

	// 获得进程信息：redisServer
	if !Method.HasEmpty(nodeRed) {
		appMap = e.getAppInfo("kernel", "node-red", nodeRed, true)
		if !Method.HasEmpty(appMap) {
			mapList = append(mapList, appMap)
		}
	}

	return mapList
}

func (e *repoLocalAppSysService) getAppInfo(appType, appName, appFeature string, isSysParam bool) map[string]interface{} {
	data, err := ProcessUtils.GetSysProcess(appFeature, isSysParam)
	if err != nil {
		return nil
	}

	data["appType"] = appType
	data["appName"] = appName
	data["appLoad"] = true

	pid := Map.GetInt64(data, "pid", 0)

	ports, err := ProcessUtils.GetProcessPort(pid)
	if err != nil {
		return nil
	}

	data["appPort"] = ports

	return data
}
